package com.itheima.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.entity.Page;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.service.EmployeeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;





    @Override
    public R<Employee> login(Employee employee) {
        //得导数据库里的数据
        Employee dbEmployee=employeeMapper.login(employee);
        //判断用户是否存在
        if (dbEmployee==null){
            return R.error("用户不存在");
        }
        //判断密码是否正确
        if (!dbEmployee.getPassword().equals(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()))){
                return R.error("密码错误");
        }
        //判断是否启动
        if (dbEmployee.getStatus()==0){
            return R.error("被禁用");
        }
return R.success(dbEmployee);

    }
    //添加用户
    @Override
    public void save(Employee employee) {
        //1. 补全密码，状态，创建、修改时间
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //把数据发给mapper层
        employeeMapper.save(employee);
    }

    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        //设置当前页与大小
        PageHelper.startPage(page,pageSize);
        //查询数据
        List<Employee> employeeList=employeeMapper.findByName(name);
        //创建pageInfo对象,把list集合传进去
        PageInfo<Employee> pageInfo = new PageInfo(employeeList);

//4. 把pageinfo的信息转移到Page对象
        Page<Employee> pageResult = new Page<>(pageInfo.getList(), pageInfo.getTotal(), pageInfo.getPageSize(), pageInfo.getPageNum(),pageInfo.getPages());

        return pageResult;

    }
//修改状态

    @Override
    public void update(Employee employee) {
        //设置修改时间
            employee.setUpdateTime(LocalDateTime.now());
            employeeMapper.update(employee);
    }

    @Override
    public R<Employee> findById(long id) {
       Employee employee= employeeMapper.findById(id);
       return R.success(employee);

    }
}
